package com.liang.servlet.user;

import com.liang.pojo.User;
import com.liang.service.user.UserServiceImpl;
import com.liang.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        login(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    /**
     * 用户登录
     */
    public static void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        User user = null;
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        UserServiceImpl userService = new UserServiceImpl();
        user = userService.login(userCode);


        if (user != null) {
            String password = user.getUserPassword();
            if (password.equals(userPassword)) {
                HttpSession session = req.getSession();
                session.setAttribute(Constant.USER_SESSION, user);
                resp.sendRedirect("jsp/frame.jsp");
            } else {
                req.setAttribute("error", "用户名或密码错误");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        }else {
            req.setAttribute("error", "用户名不存在");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
